<template>
    <div>
        <ShareDataTable
            v-model:table-data="tableData"
            :events="events"
            :table-columns="tableColumns"
            :table-attribute="tableAttribute"
            :show-contextmenu="contextMenuCtl"
            ref="childRef"
        >
        </ShareDataTable>

        <el-button-group class="bg">
            <el-space>
                <AddBtn
                    @click="handleAdd"
                    :formData="paramData"
                    :disabled="contractId === undefined"
                ></AddBtn>
                <DelBtn
                    @click="handleDelete"
                    :disabled="contractId === undefined"
                ></DelBtn>
            </el-space>
        </el-button-group>
    </div>
    <div>
        <el-dialog
            v-model="dialogUpdateVisible"
            title="委托费用维护"
            draggable
            destroy-on-close
            :center="true"
        >
            <NormalForm
                :formOptions="formOptions"
                :formItems="formItems"
                :rules="rules"
                :form-data="paramData"
                :createActionName="createActionName"
                :updateActionName="updateActionName"
                :unInitField="['contract_id']"
                @create="onAdded"
                @update="onUpdated"
                @close="onCloseDialog"
            >
            </NormalForm>
        </el-dialog>
    </div>    
</template>
<script setup lang="ts" name="ContractFeedets">
import { formatDate, initObjectProperty, pickFormFromTable, transFormatter } from '@/common/tools';
import { FormFieldItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import { FeedetModel } from '@/common/types/business';
import { tableColumnDefault } from '@/hooks/useTable';
import { useAppStore } from '@/store/app';
import { storeToRefs } from 'pinia';
import { ref, reactive } from 'vue';
import ShareDataTable from '@/components/tables/ShareDataTable.vue';
import { ElMessage, ElMessageBox, FormRules } from 'element-plus';
import { findIndex, forEach, forEachRight, includes, omit } from 'lodash';
const contractId = defineModel<number | undefined>('contractId', {
    default: undefined,
});
const tableData = defineModel<Array<FeedetModel>>('tableData');
const childRef = ref<InstanceType<typeof ShareDataTable>>();    
const paramData = ref<FeedetModel>({});
const dialogUpdateVisible = ref(false);
const {
    cntrOwner,
    client,
    feecod,
    SelectOptionFeeInOut,
    SelectOptionYN,
    currency,
} = storeToRefs(useAppStore());
const tableAttribute = ref({
    id: 'Contract-table-contractfeedets',
    // rowKey: 'id',
    height: 400,
});
const contextMenuCtl = ref(false);
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'fee_unit_cod') {
        data = client.value;
    } else if (column['property'] === 'fee_cod') {
        data = feecod.value;
    } else if (column['property'] === 'fee_in_out') {
        data = SelectOptionFeeInOut.value;
    } else if (column['property'] === 'currency_cod') {
        data = currency.value;
    } else if (column['property'] === 'fee_owner') {
        data = cntrOwner.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const rules = reactive<FormRules>({
    fee_unit_cod: [{ required: true, message: '请选择客户', trigger: 'blur' }],
    fee_owner: [{ required: true, message: '请选择成本中心', trigger: 'blur' }],
    fee_typ_cod: [
        { required: true, message: '请选择费用类型', trigger: 'blur' },
    ],

    cascaderfeecod: [
        { required: true, message: '请选择费目', trigger: 'blur' },
    ],
    amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
    currency_cod: [{ required: true, message: '请选择货币', trigger: 'blur' }],

    fee_tim: [{ required: true, message: '请选择计费日期', trigger: 'blur' }],
    fee_in_out: [
        { required: true, message: '请选择收付类型', trigger: 'blur' },
    ],
});
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'fee_unit_cod',
        label: '客户',
        fixed: 'left',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: client.value,
        width: 280,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'fee_owner',
        label: '成本中心',
        fixed: 'left',
        sortable: true,
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 280,
    },
    
    
    {
        ...tableColumnDefault,
        // isHidden: true,
        order: 5,
        prop: 'fee_cod',
        fixed: 'left',
        label: '费目',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: feecod.value,
        sortable: true,
        width: 100,
        noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 7,
        prop: 'fee_in_out',
        label: '收付',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionFeeInOut.value,
        sortable: true,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 8,
        prop: 'currency_cod',
        label: '币种',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: currency.value,
        sortable: true,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'fee_value',
        label: '单价',
        formFieldItemType: 'number',
        sortable: true,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 10,
        prop: 'fee_ton',
        label: '数量',
        formFieldItemType: 'number',
        sortable: true,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'amount',
        label: '金额',
        formFieldItemType: 'number',
        sortable: true,
        width: 130,
    },
    
    {
        ...tableColumnDefault,
        order: 13,
        prop: 'fee_tim',
        label: '计费日期',
        formatter: formatDate,
        formFieldItemType: 'date',
        sortable: true,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 18,
        prop: 'remark',
        label: '备注',
        sortable: true,
        width: 300,
    },
]);
const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});
const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);
const createActionName = ref('委托费用增加');
const updateActionName = ref('委托费用修改');
const handleAdd = () => {
    if (contractId.value) {
        initObjectProperty(paramData.value);
        paramData.value.contract_id = contractId.value;
        dialogUpdateVisible.value = true;
    }
};
const onAdded = (data: FeedetModel) => {
    tableData.value?.unshift(data);
};
const handleUpdated = async (data: FeedetModel) => {
    Object.assign(paramData.value, data);
    dialogUpdateVisible.value = true;
};
const onUpdated = (data: FeedetModel) => {
    const i = findIndex(tableData.value, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        Object.assign(tableData.value![i], omit(data, ['id', 'contract_id']));
    } else {
        ElMessage.error('修改失败');
    }
};
const handleDelete = async () => {
    const rows: Array<FeedetModel> =
        childRef.value?.tableRef?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return;
    }
    const ids = Array<number>();

    forEach(rows, (v: FeedetModel) => {
        ids.push(v.id as number);
    });

    const msg = '';
    const cr = await ElMessageBox.confirm(msg, '确认删除选中费用', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('委托费用删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(
                tableData.value,
                (v: FeedetModel, i: number) => {
                    if (includes(ids, v.id)) {
                        tableData.value?.splice(i, 1);
                    }
                },
            );
        }
    }
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
};
const events = {
    'row-dblclick': handleUpdated,
};
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
</style>
